package com.ytsakura.blog.service;

import com.ytsakura.blog.dao.UserRepository;
import com.ytsakura.blog.handler.NotFoundException;
import com.ytsakura.blog.pojo.User;
import com.ytsakura.blog.util.MD5Utils;
import com.ytsakura.blog.util.MyBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author YtSakura(Yin Tao)
 * @date 2020/5/29 14:40
 * @describe
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User checkUser(String username, String password) {
        User user=userRepository.findByUsernameAndPassword(username, MD5Utils.code(password));
        return user;
    }

    @Override
    public User getUser(String username) {
        return userRepository.findByUsername(username);
    }

    @Transactional
    @Override
    public User saveUser(User user) {
        user.setPassword(MD5Utils.code(user.getPassword()));
        user.setCreateTime(new Date());
        user.setAvatar("/images/avatar.png");
        user.setType(2);
        user.setUpdateTime(new Date());
        return userRepository.save(user);
    }

    @Override
    public User updateUser(Long id,User user) {
        User u = userRepository.findById(id).orElse(null);
        if (u == null){
            throw new NotFoundException("不存在该用户");
        }
        BeanUtils.copyProperties(user,u, MyBeanUtils.getNullPropertyNames(user));
        u.setUpdateTime(new Date());
        return userRepository.save(u);
    }

    @Override
    public void updateAvatar(String avatar, Long id) {
         userRepository.updateAvatar(avatar,id);
    }
}
